package com.mqtt.utils;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * MQTT工具类
 */
@Slf4j
public class MqttUtils {
    
    private static final Pattern TOPIC_PATTERN = Pattern.compile("^[^#+\\s]+$");
    private static final Pattern WILDCARD_PATTERN = Pattern.compile("^[^#\\s]*(/\\+)*(/[^#+\\s]+)*$|^[^#+\\s]+(/[^#+\\s]+)*/#$");
    
    /**
     * 生成消息ID
     */
    public static String generateMessageId() {
        return UUID.randomUUID().toString().replace("-", "");
    }
    
    /**
     * 生成客户端ID
     */
    public static String generateClientId(String prefix) {
        return prefix + "-" + System.currentTimeMillis() + "-" + 
               UUID.randomUUID().toString().substring(0, 8);
    }
    
    /**
     * 验证主题名称是否合法
     */
    public static boolean isValidTopic(String topic) {
        if (topic == null || topic.isEmpty() || topic.length() > 65535) {
            return false;
        }
        
        // 不能包含通配符
        if (topic.contains("+") || topic.contains("#")) {
            return false;
        }
        
        return TOPIC_PATTERN.matcher(topic).matches();
    }
    
    /**
     * 验证主题过滤器是否合法（可以包含通配符）
     */
    public static boolean isValidTopicFilter(String topicFilter) {
        if (topicFilter == null || topicFilter.isEmpty() || topicFilter.length() > 65535) {
            return false;
        }
        
        return WILDCARD_PATTERN.matcher(topicFilter).matches();
    }
    
    /**
     * 判断主题是否匹配过滤器
     */
    public static boolean matchTopic(String topicFilter, String topic) {
        if (!isValidTopicFilter(topicFilter) || !isValidTopic(topic)) {
            return false;
        }
        
        // 完全匹配
        if (topicFilter.equals(topic)) {
            return true;
        }
        
        // 处理通配符
        String regex = topicFilter
                .replace("+", "[^/]+")
                .replace("/#", "(/.*)?")
                .replace("/", "\\/");
        
        return Pattern.compile("^" + regex + "$").matcher(topic).matches();
    }
    
    /**
     * 从主题中提取设备ID
     * 假设主题格式: device/{deviceId}/...
     */
    public static String extractDeviceId(String topic) {
        if (topic == null || !topic.startsWith("device/")) {
            return null;
        }
        
        String[] parts = topic.split("/");
        if (parts.length >= 2) {
            return parts[1];
        }
        
        return null;
    }
    
    /**
     * 构建设备主题
     */
    public static String buildDeviceTopic(String deviceId, String suffix) {
        return "device/" + deviceId + "/" + suffix;
    }
    
    /**
     * 计算消息校验和
     */
    public static String calculateChecksum(String message) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(message.getBytes(StandardCharsets.UTF_8));
            
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            
            return sb.toString();
        } catch (Exception e) {
            log.error("Error calculating checksum", e);
            return "";
        }
    }
    
    /**
     * 格式化字节大小
     */
    public static String formatBytes(long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        } else if (bytes < 1024 * 1024) {
            return String.format("%.2f KB", bytes / 1024.0);
        } else if (bytes < 1024 * 1024 * 1024) {
            return String.format("%.2f MB", bytes / (1024.0 * 1024));
        } else {
            return String.format("%.2f GB", bytes / (1024.0 * 1024 * 1024));
        }
    }
    
    /**
     * 验证QoS级别
     */
    public static boolean isValidQos(int qos) {
        return qos >= 0 && qos <= 2;
    }
    
    /**
     * 获取默认QoS
     */
    public static int getDefaultQos() {
        return 1;
    }
}